package com.example.module.main.home.data.domain

import com.example.common.sdk.base.PageEntity
import com.example.common.sdk.entity.UIResult
import com.example.module.main.home.data.entity.ArticleEntity
import com.example.module.main.home.data.mapper.ArticleMapper
import com.example.module.main.home.data.repository.HomeRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class HomeArticleListUseCase {
    private val repository: HomeRepository by lazy { HomeRepository() }
    suspend fun queryArticleList(
        pageIndex: Int,
        size: Int
    ): Flow<UIResult<PageEntity<ArticleMapper>>> {
        return repository.queryArticleList(pageIndex, size)
            .map { uiResult ->
                val mapperPage = PageEntity<ArticleMapper>()
                //因为map 处于flow的下游，可能接收到 状态: Load Completion Error的数据
                //我们只需要 处理 Success 所以添加判断
                if (uiResult.status == UIResult.Status.Success) {
                    //目的是为了  网络实体 ArticleEntity 转换为 本地实体 ArticleMapper
                    val pageData = uiResult.data
                    mapperPage.clone(pageData)
                    val list = pageData?.list ?: mutableListOf()
                    val mapperList = mutableListOf<ArticleMapper>()
                    for (item: ArticleEntity in list) {
                        val author = if (item.author == "") item.shareUser else item.author
                        val summary = "作者：${author}\t 发布时间：${item.niceShareDate}"
                        val mapper = ArticleMapper(item.id, item.title, summary, item.link)
                        mapperList.add(mapper)
                    }
                    mapperPage.list = mapperList
                }
                return@map uiResult.clone(mapperPage)
            }
    }


}